package org.idea.qiyu.framework.web.handler;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.idea.qiyu.framework.web.model.IResponseVO;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;

/**
 * @Author linhao
 * @Date created in 3:20 下午 2021/8/31
 */
public class IResponseVOFastJsonConverter extends FastJsonHttpMessageConverter {

    private static final String CHARSET = "UTF-8";

    public IResponseVOFastJsonConverter() {
        this.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8));
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return IResponseVO.class.isAssignableFrom(clazz);
    }

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        OutputStream out = outputMessage.getBody();
        String text = obj.toString();
        out.write(text.getBytes(CHARSET));
    }
}
